const crypto = require('crypto');
const expressJwt = require('express-jwt');
const jwt = require('jsonwebtoken');
const { PRIVATE_KEY, JWT_EXPIRED } = require('./constant');
const jsonSql = require('json-sql')({
    // 'base', 'mssql', 'mysql', 'postgresql' or 'sqlite'.
    // dialect:'base',
    // 表名不加引号
    wrappedIdentifiers: false,
    // 值直接插入到sql字符串中
    separatedValues: false
});

/*
 * mds加密
 */ 
function md5(s) {
	// 注意参数需要为 String 类型，否则会出错
	return crypto.createHash('md5').update(String(s)).digest('hex');
}

/*
 * 路由的token验证及解析
 */
const jwtAuth = expressJwt({
	secret: PRIVATE_KEY,
	// 设置为false就不进行校验了，游客也可以访问
	credentialsRequired: true,
	algorithms: ['HS256']
}).unless({
	// 设置 jwt 认证白名单
	path: ['/', '/static', '/user/login', '/user/register']
});

/*
 * 生成token
 */ 
function sign(payload){
	let token = jwt.sign(
		payload,
		PRIVATE_KEY,
		{ expiresIn: JWT_EXPIRED }
	);
	return token;
}

/*
 * 解析token
 */ 
function decode(req) {
	const authorization = req.get('Authorization');
	let token = '';
	if (authorization.indexOf('Bearer') >= 0) {
		token = authorization.replace('Bearer ', '');
	} else {
		token = authorization;
	}
	return jwt.verify(token, PRIVATE_KEY);
}

module.exports = {
	md5,
	jwtAuth,
	decode,
	sign,
	jsonSql
}